package main

import (
	"context"
	"flag"
	"fmt"
	"os"

	"github.com/google/subcommands"
	"golang_study/internal/batch_kube"
	"golang_study/internal/util"
)

type getCmd struct {
	ns          string
	interactive bool
}

type delCmd struct {
	ns          string
	interactive bool
}

func (*delCmd) Name() string     { return "del" }
func (*delCmd) Synopsis() string { return "Delete resources." }
func (*delCmd) Usage() string {
	return `Usage: Delete resource.
del [-n ns|-i] pod|configmap|...:
`
}
func (p *delCmd) SetFlags(f *flag.FlagSet) {
	f.StringVar(&p.ns, "n", "", "specify namespace.")
	f.BoolVar(&p.interactive, "i", false, "specify interactive mode.")
}

func (p *delCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
	kubePath := util.InitConfig()
	c := util.NewConnect(kubePath)
	if len(f.Args()) < 1 {
		return subcommands.ExitFailure
	}

	argsList := util.SplitArgs(f.Args())

	for _, arg := range argsList.Resources {
		switch arg {
		case "pod", "po":
			batch_kube.DelPods(p.ns, argsList.Arguments, p.interactive, c)
		case "configmap", "cm":
			batch_kube.DelConfigmaps(p.ns, argsList.Arguments, p.interactive, c)
		default:
			fmt.Printf("%s is invalid.", arg)
			return subcommands.ExitFailure
		}
	}
	return subcommands.ExitSuccess
}

func (*getCmd) Name() string     { return "get" }
func (*getCmd) Synopsis() string { return "Get resources." }
func (*getCmd) Usage() string {
	return `get [-n ns] pod/configmap/...:
  Get resource.
`
}

func (p *getCmd) SetFlags(f *flag.FlagSet) {
	f.StringVar(&p.ns, "n", "", "specify namespace")
	f.BoolVar(&p.interactive, "i", false, "specify interactive mode")
}

func (p *getCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
	kubePath := util.InitConfig()
	c := util.NewConnect(kubePath)

	if len(f.Args()) < 1 {
		return subcommands.ExitFailure
	}

	argsList := util.SplitArgs(f.Args())

	for _, r := range argsList.Resources {
		switch r {
		case "pod", "po":
			batch_kube.GetPods(p.ns, c)
		case "configmap", "cm":
			batch_kube.GetConfigmap(p.ns, c)
		default:
			fmt.Printf("%s is invalid.", r)
			return subcommands.ExitFailure
		}
	}
	return subcommands.ExitSuccess
}

func main() {
	subcommands.Register(subcommands.HelpCommand(), "")
	subcommands.Register(subcommands.FlagsCommand(), "")
	subcommands.Register(subcommands.CommandsCommand(), "")
	subcommands.Register(&getCmd{}, "")
	subcommands.Register(&delCmd{}, "")

	flag.Parse()
	ctx := context.Background()
	os.Exit(int(subcommands.Execute(ctx)))
}
